<?php

declare(strict_types=1);

namespace App\Library\Task;


use App\Constants\ErrorCode;
use App\Exception\AppException;
use App\Library\Log\Log;
use App\Library\Task\library\queue\QueueServer;
use Hyperf\Utils\ApplicationContext;
use Swoole\Runtime;

class QueueBase
{
    private $maxRunTime = 295;

    // 消息队列中执行的
    public function execute($name)
    {
        co(function () use ($name) {
            $this->startTask($name);
        });
    }

    public function startTask($driver_name)
    {

        Runtime::enableCoroutine();

        $config = config('goods.task_drivers_default.queue_list');
        try {
            echo '执行开始:' . $driver_name . '-' . time() . PHP_EOL;

            $task = $config[$driver_name];

            if ($task['open']) {

                $worker = ApplicationContext::getContainer()->get(QueueServer::class);

                $timer = time();
                // 执行的类对象
                $logicObj = new $task['logic'];

                // 获取队列任务池列表
                $queues = $worker->scan($driver_name);
                while (true) {
                    // 获取任务池的一个任务
                    $content = $worker->pop($queues, 10);

                    // 执行任务
                    if ($content && is_array($content)) {
                        // 执行任务的方法名称
                        $method = key($content);
                        // 数据
                        $arg = current($content);
                        if (!$method || !is_object($logicObj)) {
                            continue;
                        }
                        // 开始执行时间
                        $queueTaskStart = microtime(TRUE);
                        if (is_callable(array($logicObj,$method))){//判断方法是否在类里定义
//                            Log::info(new AppException(ErrorCode::TASK_RECORD), '队列执行数据记录：'.json_encode($arg));
                            $logicObj->$method($arg);
                        }

                        // 结束执行时间
                        $queueTaskEnd = microtime(TRUE);
                        $timeCost = number_format(($queueTaskEnd - $queueTaskStart), 3);//消费方法耗时
                        //记录日志
                        Log::info(new AppException(ErrorCode::TASK_RECORD), '[' . $driver_name . '队列] 当前方法： ' . $method . '; 耗时：' . $timeCost);
                    }

                    $keeptimer = $this->maxRunTime - (time() - $timer);

                    //是否超过1分钟,因为定时任务1分钟执行一次
                    if ($keeptimer <= 1) {
                        echo '执行完毕:' . $driver_name . '-' . time() . PHP_EOL;
                        break;
                    }
                }
            }

        } catch (\Exception $exception) {
            Log::error($exception);
        }

    }

}